/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Company;
import entities.Market;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Juan
 */
public class MarketJpaController implements Serializable {
    private static MarketJpaController instance;
    
    public synchronized static MarketJpaController getInstance(){
        if(instance == null){
            instance = new MarketJpaController();
        }
        return instance;
    }

    public MarketJpaController() {
        this.emf = Persistence.createEntityManagerFactory("JavaApplication9PU");
    }

    public MarketJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Market market) {
        if (market.getCompanyCollection() == null) {
            market.setCompanyCollection(new ArrayList<Company>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Company> attachedCompanyCollection = new ArrayList<Company>();
            for (Company companyCollectionCompanyToAttach : market.getCompanyCollection()) {
                companyCollectionCompanyToAttach = em.getReference(companyCollectionCompanyToAttach.getClass(), companyCollectionCompanyToAttach.getId());
                attachedCompanyCollection.add(companyCollectionCompanyToAttach);
            }
            market.setCompanyCollection(attachedCompanyCollection);
            em.persist(market);
            for (Company companyCollectionCompany : market.getCompanyCollection()) {
                Market oldIdmarketOfCompanyCollectionCompany = companyCollectionCompany.getIdmarket();
                companyCollectionCompany.setIdmarket(market);
                companyCollectionCompany = em.merge(companyCollectionCompany);
                if (oldIdmarketOfCompanyCollectionCompany != null) {
                    oldIdmarketOfCompanyCollectionCompany.getCompanyCollection().remove(companyCollectionCompany);
                    oldIdmarketOfCompanyCollectionCompany = em.merge(oldIdmarketOfCompanyCollectionCompany);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Market market) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Market persistentMarket = em.find(Market.class, market.getId());
            Collection<Company> companyCollectionOld = persistentMarket.getCompanyCollection();
            Collection<Company> companyCollectionNew = market.getCompanyCollection();
            Collection<Company> attachedCompanyCollectionNew = new ArrayList<Company>();
            /*for (Company companyCollectionNewCompanyToAttach : companyCollectionNew) {
                companyCollectionNewCompanyToAttach = em.getReference(companyCollectionNewCompanyToAttach.getClass(), companyCollectionNewCompanyToAttach.getId());
                attachedCompanyCollectionNew.add(companyCollectionNewCompanyToAttach);
            }*/
            companyCollectionNew = attachedCompanyCollectionNew;
            market.setCompanyCollection(companyCollectionNew);
            market = em.merge(market);
            for (Company companyCollectionOldCompany : companyCollectionOld) {
                if (!companyCollectionNew.contains(companyCollectionOldCompany)) {
                    companyCollectionOldCompany.setIdmarket(null);
                    companyCollectionOldCompany = em.merge(companyCollectionOldCompany);
                }
            }
            for (Company companyCollectionNewCompany : companyCollectionNew) {
                if (!companyCollectionOld.contains(companyCollectionNewCompany)) {
                    Market oldIdmarketOfCompanyCollectionNewCompany = companyCollectionNewCompany.getIdmarket();
                    companyCollectionNewCompany.setIdmarket(market);
                    companyCollectionNewCompany = em.merge(companyCollectionNewCompany);
                    if (oldIdmarketOfCompanyCollectionNewCompany != null && !oldIdmarketOfCompanyCollectionNewCompany.equals(market)) {
                        oldIdmarketOfCompanyCollectionNewCompany.getCompanyCollection().remove(companyCollectionNewCompany);
                        oldIdmarketOfCompanyCollectionNewCompany = em.merge(oldIdmarketOfCompanyCollectionNewCompany);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = market.getId();
                if (findMarket(id) == null) {
                    throw new NonexistentEntityException("The market with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Market market;
            try {
                market = em.getReference(Market.class, id);
                market.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The market with id " + id + " no longer exists.", enfe);
            }
            Collection<Company> companyCollection = market.getCompanyCollection();
            for (Company companyCollectionCompany : companyCollection) {
                companyCollectionCompany.setIdmarket(null);
                companyCollectionCompany = em.merge(companyCollectionCompany);
            }
            em.remove(market);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Market> findMarketEntities() {
        return findMarketEntities(true, -1, -1);
    }

    public List<Market> findMarketEntities(int maxResults, int firstResult) {
        return findMarketEntities(false, maxResults, firstResult);
    }

    private List<Market> findMarketEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Market.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Market findMarket(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Market.class, id);
        } finally {
            em.close();
        }
    }

    public int getMarketCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Market> rt = cq.from(Market.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
